import { http } from 'msw';

const mockData = [
  { id: 1, name: 'Mock User' }
];

export const handlers = [
  http.get('/api/contacts/:contactId', ({ params }) => {
    const contact = mockData.find(item => item.id === Number(params.contactId));
    return new Response(
      JSON.stringify(contact || {
        id: params.contactId,
        name: 'Mock User',
      }),
    );
  }),
  http.post('/api/contacts/:contactId', async ({ params, request }) => {
    const formData = await request.formData();
    const updatedNameEntry = formData.get('name');
    const updatedName = typeof updatedNameEntry === 'string' ? updatedNameEntry : 'Updated Mock User';
    const contactId = Number(params.contactId);
    const contactIndex = mockData.findIndex(item => item.id === contactId);

    if (contactIndex !== -1) {
      mockData[contactIndex].name = updatedName;
    } else {
      mockData.push({ id: contactId, name: updatedName });
    }

    return new Response(
      JSON.stringify({
        id: contactId,
        name: updatedName,
      }),
    );
  }),
];
